<template>
  <div class="sketchpad-container">
    <div class="main-title">简易像素风画板</div>
    <div class="container">
      <div class="icon-lib">
        <div v-for="(item, index) in iconList" :key="index" class="icon-item">
          <img
            draggable="true"
            @dragstart="onDragStart(item)"
            @dragend="onDragEnd"
            :src="item.icon"
            alt=""
          />
        </div>
      </div>
      <div class="canvas-container">
        <canvas
          ref="canvas"
          :width="canvasSize"
          :height="canvasSize"
          @mousedown="handleMouseDown"
          @mousemove="handleMouseMove"
          @mouseup="handleMouseUp"
          @mouseleave="handleMouseUp"
          @drop="onDrop"
          @dragenter="onDragEnter"
          @dragover="onDragOver"
          :class="currentTool"
        ></canvas>
      </div>
      <div class="toolbar-container">
        <div class="tool-list">
          <div class="title">工具栏</div>
          <div class="button">
            <el-button
              size="small"
              @click="selectTool('select')"
              :type="currentTool === 'select' ? 'primary' : 'info'"
              round
              >选择</el-button
            >
          </div>
          <div class="button">
            <el-button size="small" @click="clearCanvas" type="danger" round
              >清空</el-button
            >
          </div>
          <div class="button">
            <el-button
              size="small"
              @click="selectTool('pen')"
              :type="currentTool === 'pen' ? 'primary' : 'info'"
              round
              >画笔</el-button
            >
          </div>
          <div class="button">
            <el-button
              size="small"
              @click="selectTool('eraser')"
              :type="currentTool === 'eraser' ? 'primary' : 'info'"
              round
              >橡皮</el-button
            >
          </div>
          <div class="button">
            <el-button
              size="small"
              @click="selectTool('rectangle')"
              :type="currentTool === 'rectangle' ? 'primary' : 'info'"
              round
              >矩形</el-button
            >
          </div>
          <div class="button">
            <el-button
              size="small"
              @click="selectTool('ellipse')"
              :type="currentTool === 'ellipse' ? 'primary' : 'info'"
              round
              >椭圆形</el-button
            >
          </div>
          <div class="button">
            <el-button
              size="small"
              @click="selectTool('image')"
              :type="currentTool === 'image' ? 'primary' : 'info'"
              round
              >图片</el-button
            >
          </div>
          <div class="button">
            <el-button
              size="small"
              @click="selectTool('text')"
              :type="currentTool === 'text' ? 'primary' : 'info'"
              round
              >文字</el-button
            >
          </div>
        </div>
        <div class="attribute-container">
          <div v-if="currentTool === 'text'" class="text-input">
            <div class="title">文本</div>
            <div class="input-container">
              <div class="block-row">
                <span>文字大小</span>
                <el-input-number
                  v-model="fontSize"
                  :min="8"
                  :max="100"
                  step-strictly
                  size="small"
                  label="文字大小"
                ></el-input-number>
              </div>
              <div style="margin-top: 10px" class="block-row">
                <span>文本内容</span>
                <el-input
                  v-model="textInput"
                  style="width: 100%"
                  type="textarea"
                  :autosize="autoSize"
                  placeholder="输入文本内容"
                  @keyup.enter="addTextToLayer"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="color-input">
            <div class="title">颜色</div>
            <div class="input-container">
              <div class="block">
                <el-color-picker v-model="color"></el-color-picker>
                <span>颜色</span>
              </div>
              <div class="block">
                <el-color-picker v-model="fillColor"></el-color-picker>
                <span>填充颜色</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <el-button size="small" @click="exportImage" type="primary" round
        >导出图片</el-button
      >
    </div>
    <!-- <span :style="'white-space: pre;font:' + fontSize + 'px Arial'">{{
      textInput
    }}</span> -->
    <canvas ref="targetCanvas" width="32" height="32"></canvas>
  </div>
</template>

<script>
import iconList from "@/api/icon-lib";
export default {
  data() {
    return {
      iconList: [],
      currentDragItem: null,
      canvasSize: 256, // 32 * 8px
      pixelSize: 8, // 每个像素块的大小
      color: "#000000",
      fillColor: "#ffffff",
      fontSize: 45,
      autoSize: { minRows: 3, maxRows: 6 },
      layers: [
        {
          grid: Array.from({ length: 32 }, () => Array(32).fill(false)),
          colors: Array.from({ length: 32 }, () => Array(32).fill("#ffffff")),
          texts: [], // 存储文本信息
        },
      ],
      currentLayerIndex: 0,
      currentTool: "select", // 当前工具
      isDrawing: false, // 是否正在绘制
      lastPosition: null, // 上一次绘制的位置
      dragging: false, // 是否正在拖动
      dragStartPos: { x: 0, y: 0 }, // 开始拖动时的鼠标位置
      selectedPixels: [], // 记录选中的像素点
      selectedTexts: [], // 记录选中的文本
      tempGrid: [], // 临时存储当前状态的网格
      tempColors: [], // 临时存储当前状态的颜色
      movedPixels: {}, // 记录移动后的像素点位置
      textInput: "", // 输入的文本内容
      addingText: false, // 是否正在添加文本
      textPosition: { x: 0, y: 0 }, // 文本位置
      textDragOffset: { x: 0, y: 0 }, // 文本拖动偏移量
      rectangleStart: null, // 矩形开始位置
      rectangleEnd: null, // 矩形结束位置
      selectionBox: null, // 用于绘制选择框的临时元素
    };
  },
  computed: {
    currentLayer() {
      return this.layers[this.currentLayerIndex];
    },
  },
  methods: {
    onDragStart(icon) {
      // console.log('onDragStart ',icon);
      this.currentDragItem = icon;
    },
    onDragEnd() {
      this.currentDragItem = null;
      // console.log(`onDragEnd`);
    },
    onDrop() {
      if (!this.currentDragItem) {
        return;
      }
      const img = new Image();
      img.src = this.currentDragItem.icon;
      this.addNewLayerFromImage(img);
    },
    onDragEnter(event) {
      event.preventDefault();
    },
    onDragOver(event) {
      event.preventDefault();
    },
    exportImage() {
      // 获取两个Canvas元素
      const sourceCanvas = this.$refs.canvas;
      const targetCanvas = this.$refs.targetCanvas;

      // 获取对应的绘图上下文
      const sourceCtx = sourceCanvas.getContext("2d");
      const targetCtx = targetCanvas.getContext("2d");

      // 提取每个8x8格子中心的1x1像素，并绘制到目标Canvas
      for (let i = 0; i < 32; i++) {
        for (let j = 0; j < 32; j++) {
          const centerX = i * this.pixelSize + this.pixelSize / 2;
          const centerY = j * this.pixelSize + this.pixelSize / 2;

          // 获取像素数据
          const pixelData = sourceCtx.getImageData(centerX, centerY, 1, 1).data;

          // 创建ImageData对象用于目标Canvas
          const newPixelData = new ImageData(1, 1);
          newPixelData.data.set(pixelData);

          // 绘制到目标Canvas
          targetCtx.putImageData(newPixelData, i, j);
        }
      }
    },

    selectTool(tool) {
      if (tool === "text") {
        this.addingText = true;
      } else {
        this.addingText = false;
      }
      this.currentTool = tool;
      if (tool === "image") {
        this.updateImageFile();
      }
    },
    updateImageFile() {
      // 每次点击按钮时创建新的input元素
      const inputElement = document.createElement("input");
      inputElement.type = "file";
      inputElement.accept = "image/*";

      // 为input元素添加change事件监听器，用于处理选择图片后的操作
      inputElement.addEventListener("change", (event) => {
        this.handleImageUpload(event);
      });
      // 触发input元素的点击，弹出文件选择框
      inputElement.click();
      this.currentTool = "select";
    },
    handleMouseDown(event) {
      // console.log('handleMouseDown',this.dragging);
      const position = this.getGridPosition(event);
      if (this.currentTool === "select") {
        for (let i = this.layers.length - 1; i >= 0; i--) {
          if (this.isPixelDrawn(position, i)) {
            this.currentLayerIndex = i;
            this.dragging = true;
            this.dragStartPos = position;
            this.selectedTexts = [];
            this.selectedPixels = this.getSelectedPixels(i); // 记录所有已绘制的像素点
            this.tempGrid = JSON.parse(JSON.stringify(this.layers[i].grid)); // 备份当前网格状态
            this.tempColors = JSON.parse(JSON.stringify(this.layers[i].colors)); // 备份当前颜色状态
            break;
          }
        }
        console.log(this.layers);
        console.log(position);
        // 检查是否选中文本
        for (let i = this.layers.length - 1; i >= 0; i--) {
          for (const text of this.layers[i].texts) {
            if (
              position.x >= text.position.x &&
              position.x <= text.position.x + text.width &&
              position.y >= text.position.y &&
              position.y <= text.position.y + text.height
            ) {
              this.currentLayerIndex = i;
              this.selectedTexts.push(text);
              this.selectedPixels = [];
              this.dragging = true;
              this.dragStartPos = position;
              this.textDragOffset = {
                x: position.x - text.position.x,
                y: position.y - text.position.y,
              };
              return;
            }
          }
        }
      } else if (this.currentTool === "text") {
        this.textPosition = position;
        this.addingText = true;
        this.drawTextPreview();
      } else if (
        this.currentTool === "rectangle" ||
        this.currentTool === "ellipse"
      ) {
        this.rectangleStart = position;
        this.rectangleEnd = position;
        this.ellipseStart = position;
        this.ellipseEnd = position;
        this.isDrawing = true;
      } else {
        this.isDrawing = true;
        this.lastPosition = position;
        this.applyTool(event);
      }
    },
    handleMouseMove(event) {
      // console.log('handleMouseMove',this.dragging);
      if (!this.dragging && !this.isDrawing && !this.addingText) return;

      const position = this.getGridPosition(event);
      if (this.dragging) {
        if (this.selectedPixels.length > 0) {
          const offsetX = position.x - this.dragStartPos.x;
          const offsetY = position.y - this.dragStartPos.y;
          // 计算新的边界限制
          let minX = Infinity;
          let minY = Infinity;
          let maxX = -Infinity;
          let maxY = -Infinity;
          for (const pixel of this.selectedPixels) {
            const newX = pixel.x + offsetX;
            const newY = pixel.y + offsetY;
            minX = Math.min(minX, newX);
            minY = Math.min(minY, newY);
            maxX = Math.max(maxX, newX);
            maxY = Math.max(maxY, newY);
          }
          // 确保新的边界不会超出画布范围
          const offsetAdjustX =
            Math.max(0, -minX) +
            Math.min(0, this.canvasSize / this.pixelSize - maxX - 1);
          const offsetAdjustY =
            Math.max(0, -minY) +
            Math.min(0, this.canvasSize / this.pixelSize - maxY - 1);

          // 清空当前网格和颜色
          for (let y = 0; y < this.canvasSize / this.pixelSize; y++) {
            for (let x = 0; x < this.canvasSize / this.pixelSize; x++) {
              this.currentLayer.grid[y][x] = false;
              this.currentLayer.colors[y][x] = "#ffffff";
            }
          }

          // 更新每个选中像素点的新位置
          for (const pixel of this.selectedPixels) {
            const newX = pixel.x + offsetX + offsetAdjustX;
            const newY = pixel.y + offsetY + offsetAdjustY;
            this.movedPixels[`${pixel.x},${pixel.y}`] = { x: newX, y: newY };

            // 设置颜色
            if (
              newX >= 0 &&
              newX < this.canvasSize / this.pixelSize &&
              newY >= 0 &&
              newY < this.canvasSize / this.pixelSize
            ) {
              this.currentLayer.grid[newY][newX] = true; // 设置新位置
              this.currentLayer.colors[newY][newX] =
                this.tempColors[pixel.y][pixel.x];
            }
          }
        }

        // 更新每个选中文本的新位置
        for (const text of this.selectedTexts) {
          text.position.x = position.x - this.textDragOffset.x;
          text.position.y = position.y - this.textDragOffset.y;
        }

        this.drawCanvas();
      } else if (this.isDrawing) {
        if (
          this.currentTool === "rectangle" ||
          this.currentTool === "ellipse"
        ) {
          this.rectangleEnd = position;
          this.ellipseEnd = position;
          this.drawSelectionBox();
        } else {
          const currentPosition = position;
          if (this.lastPosition) {
            this.interpolate(this.lastPosition, currentPosition);
          }
          this.lastPosition = currentPosition;
        }
      }
    },
    handleMouseUp() {
      // console.log('handleMouseUp',this.dragging);
      if (this.dragging) {
        if (this.selectedPixels.length > 0) {
          if (Object.keys(this.movedPixels).length == 0) {
            this.initDefaultValue();
            return;
          }
          // 清空当前网格和颜色
          for (let y = 0; y < this.canvasSize / this.pixelSize; y++) {
            for (let x = 0; x < this.canvasSize / this.pixelSize; x++) {
              this.currentLayer.grid[y][x] = false;
              this.currentLayer.colors[y][x] = "#ffffff";
            }
          }

          // 更新每个选中像素点的新位置
          for (const key in this.movedPixels) {
            const { x, y } = this.movedPixels[key];
            if (
              x >= 0 &&
              x < this.canvasSize / this.pixelSize &&
              y >= 0 &&
              y < this.canvasSize / this.pixelSize
            ) {
              this.currentLayer.grid[y][x] = true; // 设置新位置
              this.currentLayer.colors[y][x] =
                this.tempColors[parseInt(key.split(",")[1])][
                  parseInt(key.split(",")[0])
                ]; // 设置颜色
            }
          }
        }

        // 更新每个选中文本的新位置
        for (const text of this.selectedTexts) {
          text.position.x = Math.max(
            0,
            Math.min(
              this.canvasSize / this.pixelSize - text.width,
              text.position.x
            )
          );
          text.position.y = Math.max(
            0,
            Math.min(
              this.canvasSize / this.pixelSize - text.height,
              text.position.y
            )
          );
        }
        // 重新设置备份状态
        this.tempGrid = JSON.parse(JSON.stringify(this.currentLayer.grid));
        this.tempColors = JSON.parse(JSON.stringify(this.currentLayer.colors));
        this.drawCanvas();
      } else if (this.addingText) {
        this.addTextToLayer();
      } else if (this.isDrawing) {
        if (this.currentTool === "rectangle") {
          this.drawRectangles();
        } else if (this.currentTool === "ellipse") {
          this.drawEllipses();
        }
      }
      this.initDefaultValue();
    },
    initDefaultValue() {
      this.movedPixels = {}; // 清空移动后的像素点位置
      this.selectedTexts = [];
      this.isDrawing = false;
      this.lastPosition = null;
      this.dragging = false;
      this.addingText = false;
      this.textDragOffset = { x: 0, y: 0 }; // 重置拖动偏移量
      this.rectangleStart = null;
      this.rectangleEnd = null;
      this.ellipseStart = null;
      this.ellipseEnd = null;
      this.clearSelectionBox(); // 清除选择框
    },
    getGridPosition(event) {
      const canvas = this.$refs.canvas;
      const rect = canvas.getBoundingClientRect();
      const x = Math.floor((event.clientX - rect.left) / this.pixelSize);
      const y = Math.floor((event.clientY - rect.top) / this.pixelSize);
      return { x, y };
    },
    interpolate(start, end) {
      const dx = Math.abs(end.x - start.x);
      const dy = Math.abs(end.y - start.y);
      const sx = start.x < end.x ? 1 : -1;
      const sy = start.y < end.y ? 1 : -1;
      let err = dx - dy;

      let x = start.x;
      let y = start.y;

      while (x !== end.x || y !== end.y) {
        this.updateGrid(x, y);

        const e2 = err * 2;
        if (e2 > -dy) {
          err -= dy;
          x += sx;
        }
        if (e2 < dx) {
          err += dx;
          y += sy;
        }
      }

      this.updateGrid(end.x, end.y);
      this.drawCanvas();
    },
    drawEllipses() {
      const startX = Math.min(this.ellipseStart.x, this.ellipseEnd.x);
      const startY = Math.min(this.ellipseStart.y, this.ellipseEnd.y);
      let endX = Math.max(this.ellipseStart.x, this.ellipseEnd.x);
      let endY = Math.max(this.ellipseStart.y, this.ellipseEnd.y);
      endX = Math.min(endX, this.canvasSize / this.pixelSize - 1);
      endY = Math.min(endY, this.canvasSize / this.pixelSize - 1);
      if (!this.currentLayer) {
        this.layers.push({
          grid: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill(false)
          ),
          colors: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill("#ffffff")
          ),
          texts: [],
        });
        this.currentLayerIndex = this.layers.length - 1;
      }

      const centerX = (startX + endX) / 2;
      const centerY = (startY + endY) / 2;
      const radiusX = Math.max(1, (endX - startX) / 2);
      const radiusY = Math.max(1, (endY - startY) / 2);

      // 绘制内部红色填充
      for (let y = 0; y < this.canvasSize / this.pixelSize; y++) {
        for (let x = 0; x < this.canvasSize / this.pixelSize; x++) {
          const distanceSquared =
            (x - centerX) ** 2 / radiusX ** 2 +
            (y - centerY) ** 2 / radiusY ** 2;
          if (distanceSquared <= 1) {
            this.currentLayer.grid[y][x] = true;
            this.currentLayer.colors[y][x] = this.fillColor || "#ff0000";
          }
        }
      }

      // 绘制边框
      for (let y = 0; y < this.canvasSize / this.pixelSize; y++) {
        for (let x = 0; x < this.canvasSize / this.pixelSize; x++) {
          const distanceSquared =
            (x - centerX) ** 2 / radiusX ** 2 +
            (y - centerY) ** 2 / radiusY ** 2;
          if (Math.abs(distanceSquared - 1) < 0.1) {
            this.currentLayer.grid[y][x] = true;
            this.currentLayer.colors[y][x] = this.color || "#000000";
          }
        }
      }
      this.drawCanvas();
    },
    drawRectangles() {
      const startX = Math.min(this.rectangleStart.x, this.rectangleEnd.x);
      const startY = Math.min(this.rectangleStart.y, this.rectangleEnd.y);
      let endX = Math.max(this.rectangleStart.x, this.rectangleEnd.x);
      let endY = Math.max(this.rectangleStart.y, this.rectangleEnd.y);
      endX = Math.min(endX, this.canvasSize / this.pixelSize - 1);
      endY = Math.min(endY, this.canvasSize / this.pixelSize - 1);
      if (!this.currentLayer) {
        this.layers.push({
          grid: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill(false)
          ),
          colors: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill("#ffffff")
          ),
          texts: [],
        });
        this.currentLayerIndex = this.layers.length - 1;
      }

      // 绘制内部红色填充
      for (let y = startY + 1; y < endY; y++) {
        for (let x = startX + 1; x < endX; x++) {
          this.currentLayer.grid[y][x] = true;
          this.currentLayer.colors[y][x] = this.fillColor || "#ff0000";
        }
      }
      const borderColor = this.color || "#000000";
      // 绘制边框
      // 左上角
      this.currentLayer.grid[startY][startX] = true;
      this.currentLayer.grid[startY][startX + 1] = true;
      // this.currentLayer.grid[startY + 1][startX + 1] = true;

      this.currentLayer.colors[startY][startX] = borderColor;
      this.currentLayer.colors[startY][startX + 1] = borderColor;
      // this.currentLayer.colors[startY + 1][startX + 1] = borderColor;
      // 右上角
      this.currentLayer.grid[startY][endX] = true;
      this.currentLayer.grid[startY][endX - 1] = true;
      // this.currentLayer.grid[startY + 1][endX - 1] = true;

      this.currentLayer.colors[startY][endX] = borderColor;
      this.currentLayer.colors[startY][endX - 1] = borderColor;
      // this.currentLayer.colors[startY + 1][endX - 1] = borderColor;
      // 左下角
      this.currentLayer.grid[endY][startX] = true;
      this.currentLayer.grid[endY][startX + 1] = true;
      // this.currentLayer.grid[endY - 1][startX + 1] = true;

      this.currentLayer.colors[endY][startX] = borderColor;
      this.currentLayer.colors[endY][startX + 1] = borderColor;
      // this.currentLayer.colors[endY - 1][startX + 1] = borderColor;
      // 右下角
      this.currentLayer.grid[endY][endX] = true;
      this.currentLayer.grid[endY][endX - 1] = true;
      // this.currentLayer.grid[endY - 1][endX - 1] = true;

      this.currentLayer.colors[endY][endX] = borderColor;
      this.currentLayer.colors[endY][endX - 1] = borderColor;
      // this.currentLayer.colors[endY - 1][endX - 1] = borderColor;
      // 上边框
      for (let x = startX + 1; x < endX; x++) {
        this.currentLayer.grid[startY][x] = true;
        this.currentLayer.colors[startY][x] = borderColor;
      }

      // 下边框
      for (let x = startX + 1; x < endX; x++) {
        this.currentLayer.grid[endY][x] = true;
        this.currentLayer.colors[endY][x] = borderColor;
      }

      // 左边框
      for (let y = startY + 1; y < endY; y++) {
        this.currentLayer.grid[y][startX] = true;
        this.currentLayer.colors[y][startX] = borderColor;
      }

      // 右边框
      for (let y = startY + 1; y < endY; y++) {
        this.currentLayer.grid[y][endX] = true;
        this.currentLayer.colors[y][endX] = borderColor;
      }

      this.drawCanvas();
    },
    updateGrid(x, y) {
      if (
        x < 0 ||
        x >= this.canvasSize / this.pixelSize ||
        y < 0 ||
        y >= this.canvasSize / this.pixelSize
      )
        return;

      if (this.currentTool === "pen") {
        this.currentLayer.grid[y][x] = true;
        this.currentLayer.colors[y][x] = this.color || "#000000"; // 默认笔颜色为黑色
      } else if (this.currentTool === "eraser") {
        for (const layer of this.layers) {
          layer.grid[y][x] = false;
          layer.colors[y][x] = "#ffffff"; // 橡皮擦颜色为白色
        }
        // 删除覆盖区域内的文本
        for (const layer of this.layers) {
          layer.texts = layer.texts.filter((text) => {
            const minX = text.position.x;
            const maxX = text.position.x + text.width;
            const minY = text.position.y;
            const maxY = text.position.y + text.height;

            // 如果橡皮擦范围与文本范围有交集，则删除该文本
            return !(x >= minX && x <= maxX && y >= minY && y <= maxY);
          });
        }
      }
    },
    applyTool(event) {
      const { x, y } = this.getGridPosition(event);
      this.updateGrid(x, y);
      this.drawCanvas();
    },
    drawCanvas() {
      // console.log(this.layers);
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");

      ctx.clearRect(0, 0, this.canvasSize, this.canvasSize); // 清空画布
      // 绘制棋盘背景
      for (let y = 0; y < this.canvasSize / this.pixelSize; y++) {
        for (let x = 0; x < this.canvasSize / this.pixelSize; x++) {
          ctx.fillStyle = (x + y) % 2 === 0 ? "#f8f8f8" : "#e0e0e0";
          ctx.fillRect(
            x * this.pixelSize,
            y * this.pixelSize,
            this.pixelSize,
            this.pixelSize
          );
        }
      }

      // 绘制所有图层的内容
      for (const layer of this.layers) {
        for (let y = 0; y < this.canvasSize / this.pixelSize; y++) {
          for (let x = 0; x < this.canvasSize / this.pixelSize; x++) {
            if (layer.grid[y][x]) {
              ctx.fillStyle = layer.colors[y][x];
              ctx.fillRect(
                x * this.pixelSize,
                y * this.pixelSize,
                this.pixelSize,
                this.pixelSize
              );
            }
          }
        }

        // 绘制文本
        for (const text of layer.texts) {
          ctx.font = `${text.fontSize}px Arial`;
          ctx.fillStyle = text.color;
          const lines = text.content.split("\n");
          const lineHeight = text.lineHeight;
          lines.forEach((line, index) => {
            ctx.fillText(
              line,
              text.position.x * this.pixelSize,
              text.position.y * this.pixelSize + (index + 1) * lineHeight
            );
          });
        }
      }
    },
    isPixelDrawn(position, layerIndex = this.currentLayerIndex) {
      const { x, y } = position;
      return this.layers[layerIndex]?.grid[y]?.[x];
    },
    getSelectedPixels(layerIndex = this.currentLayerIndex) {
      const pixels = [];
      for (let y = 0; y < this.canvasSize / this.pixelSize; y++) {
        for (let x = 0; x < this.canvasSize / this.pixelSize; x++) {
          if (this.layers[layerIndex]?.grid[y]?.[x]) {
            pixels.push({ x, y });
          }
        }
      }
      return pixels;
    },
    handleImageUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        const img = new Image();
        img.src = e.target.result;
        img.onload = () => {
          this.addNewLayerFromImage(img);
        };
      };
      reader.readAsDataURL(file);
    },
    clearCanvas() {
      this.layers = [
        {
          grid: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill(false)
          ),
          colors: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill("#ffffff")
          ),
          texts: [],
        },
      ];
      this.currentLayerIndex = 0;
      this.drawCanvas(); // 重新绘制画布
    },
    addNewLayerFromImage(img) {
      const newLayer = {
        grid: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
          Array(this.canvasSize / this.pixelSize).fill(false)
        ),
        colors: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
          Array(this.canvasSize / this.pixelSize).fill("#ffffff")
        ),
        texts: [],
      };
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      canvas.width = img.width;
      canvas.height = img.height;

      // 缩放图像到实际大小
      ctx.drawImage(img, 0, 0, img.width, img.height);

      const imageData = ctx.getImageData(0, 0, img.width, img.height).data;
      for (let y = 0; y < img.height; y++) {
        for (let x = 0; x < img.width; x++) {
          const index = (y * img.width + x) * 4;
          const r = imageData[index];
          const g = imageData[index + 1];
          const b = imageData[index + 2];
          const a = imageData[index + 3];

          // 将透明度考虑进去
          if (a === 255) {
            newLayer.grid[y][x] = true;
            newLayer.colors[y][x] = `rgb(${r}, ${g}, ${b})`;
          } else {
            newLayer.grid[y][x] = false;
            newLayer.colors[y][x] = "#ffffff";
          }
        }
      }

      this.layers.push(newLayer);
      this.currentLayerIndex = this.layers.length - 1;
      this.drawCanvas();
    },
    drawTextPreview() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");

      ctx.clearRect(0, 0, this.canvasSize, this.canvasSize); // 清空画布
      this.drawCanvas(); // 重新绘制现有内容
    },
    addTextToLayer() {
      if (this.textInput.trim()) {
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext("2d");
        ctx.font = `${this.fontSize}px Arial`;
        const lines = this.textInput.split("\n");
        const { textWidth, textHeight } = this.getTextDimensions(
          this.textInput,
          `${this.fontSize}px Arial`
        );
        const lineHeight = textHeight / lines.length;
        const width = Math.ceil(textWidth / this.pixelSize);
        const height = Math.ceil(textHeight / this.pixelSize);

        // 创建新的图层用于存放文本
        const newTextLayer = {
          grid: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill(false)
          ),
          colors: Array.from({ length: this.canvasSize / this.pixelSize }, () =>
            Array(this.canvasSize / this.pixelSize).fill("#ffffff")
          ),
          texts: [
            {
              content: this.textInput,
              position: this.textPosition,
              fontSize: this.fontSize || 14,
              color: this.color || "#000000",
              width: width,
              height: height,
              textWidth,
              textHeight,
              lineHeight,
            },
          ],
        };

        this.layers.push(newTextLayer);
        this.currentLayerIndex = this.layers.length - 1;
        // this.textInput = "";
        this.currentTool = "select";
        this.drawCanvas();
      }
    },
    getTextDimensions(text, font) {
      var dummy = document.createElement("span");
      dummy.style.font = font;
      dummy.style.position = "absolute";
      dummy.style.whiteSpace = "pre";
      dummy.textContent = text;
      document.body.appendChild(dummy);

      var rect = dummy.getBoundingClientRect();

      document.body.removeChild(dummy);

      return { textWidth: rect.width, textHeight: rect.height };
    },
    drawSelectionBox() {
      if (this.selectionBox) {
        this.selectionBox.remove();
      }

      const canvas = this.$refs.canvas;
      const rect = canvas.getBoundingClientRect();

      const startX =
        Math.min(this.rectangleStart.x, this.rectangleEnd.x) * this.pixelSize;
      const startY =
        Math.min(this.rectangleStart.y, this.rectangleEnd.y) * this.pixelSize;
      const endX =
        Math.max(this.rectangleStart.x, this.rectangleEnd.x) * this.pixelSize;
      const endY =
        Math.max(this.rectangleStart.y, this.rectangleEnd.y) * this.pixelSize;

      this.selectionBox = document.createElement("div");
      this.selectionBox.style.position = "absolute";
      this.selectionBox.style.border = "1px dashed #000000";
      this.selectionBox.style.backgroundColor = "rgba(0, 0, 0, 0.1)";
      this.selectionBox.style.pointerEvents = "none"; // 不影响事件传递
      this.selectionBox.style.left = `${rect.left + startX}px`;
      this.selectionBox.style.top = `${rect.top + startY}px`;
      this.selectionBox.style.width = `${endX - startX}px`;
      this.selectionBox.style.height = `${endY - startY}px`;

      document.body.appendChild(this.selectionBox);
    },
    clearSelectionBox() {
      if (this.selectionBox) {
        this.selectionBox.remove();
        this.selectionBox = null;
      }
    },
  },
  created() {
    this.iconList = iconList;
    // console.log(this.iconList);
  },
  mounted() {
    this.clearCanvas();
  },
};
</script>

<style lang="less" scoped>
.sketchpad-container {
  .main-title {
    width: 100%;
    margin-bottom: 10px;
    font-size: 18px;
    font-weight: 600;
  }
  .container {
    display: flex;
    flex-direction: row;
    justify-content: center;
    .icon-lib {
      width: 300px;
      margin-right: 50px;
      padding: 0 12px;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      .icon-item {
        width: 24%;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        img {
          width: 24px;
        }
      }
    }
    .toolbar-container {
      margin-left: 50px;
      border: 2px solid;
      border-radius: 10px;
      width: 300px;
      display: flex;
      flex-direction: column;
      align-items: center;
      flex-wrap: wrap;
      .title {
        width: 100%;
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: 600;
      }
      .tool-list {
        padding: 12px;
        display: flex;
        justify-content: center;
        flex-direction: row;
        align-items: center;
        flex-wrap: wrap;
        .button {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          width: 49%;
          margin-bottom: 10px;
          button {
            min-width: 70px;
            padding: 9px 0;
          }
          &.main-button {
            width: 98%;
          }
        }
      }
      .attribute-container {
        width: 100%;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        flex-wrap: wrap;
        .text-input,
        .color-input {
          width: 100%;
          border-top: 2px solid;
          padding: 12px 0;
          margin-bottom: 10px;
          .input-container {
            display: flex;
            flex-direction: row;
            justify-content: space-evenly;
            flex-wrap: wrap;
            padding: 0 12px;
            .block {
              display: flex;
              flex-direction: column;
              align-items: center;
              span {
                font-size: 12px;
                color: #909399;
              }
            }
            .block-row {
              width: 100%;
              display: flex;
              flex-direction: column;
              span {
                width: 48px;
                padding-bottom: 6px;
                font-size: 12px;
                color: #909399;
              }
            }
          }
        }
      }
    }
  }
}
canvas {
  border: 1px solid #ccc;
  display: block;
  margin: 0 auto;
  cursor: auto;
  image-rendering: pixelated; /* 确保像素风格显示 */
  &.pen {
    cursor: url("@/assets/pen.svg") 0 20, crosshair;
  }
  &.eraser {
    cursor: url("@/assets/eraser.svg") 8 20, cell;
  }
  &.text {
    cursor: text;
  }
}
</style>



